//
//  Controller.m
//  YaoHeAPP
//
//  Created by mac on 15/11/23.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "Controller.h"
#import "LoginVC.h"
#import "ViewController.h"
#import "JSONKit.h"
#import "SVProgressHUD.h"
#import "Reachability.h"
#import "ShowMessageView.h"
@implementation Controller


//发送网络请求
+(void)requestWithURL:(NSString*)urlString jsondic:(NSDictionary*)dic finishBlock:(void(^)(ClassData*))complete
{
    //是模糊查询的不要加载动画
    if (![urlString isEqualToString:@"AppCompanyRegist/PostlikelyCompanyName?from=app"]) {
        
        [SVProgressHUD showWithStatus:@"正在拼命加载......"];
    }
    
//    [SVProgressHUD showWithStatus:@"正在拼命加载......"];
    
    NSString*url=[NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,urlString];
    AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager manager];
    if (dic==nil)
    {
        [manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
            [SVProgressHUD dismiss];
            ClassData*classData=[[ClassData alloc]initWith:responseObject];
            
            if ([classData.number isEqualToNumber:[NSNumber numberWithInteger:2]])
            {
                // [[NSUserDefaults standardUserDefaults]setObject:@"成功" forKey:@"状态"];
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"状态"];
                ViewController*vc=[ViewController new];
                UIWindow*window=[UIApplication sharedApplication].delegate.window;
                window.rootViewController=vc;
                return ;
            }
            complete(classData);
        } failure:^(AFHTTPRequestOperation*operation, NSError *error) {
            [SVProgressHUD dismiss];
            
            NSLog(@"请求失败的原因：%@",error);
            Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
            switch ([reach currentReachabilityStatus]) {
                case NotReachable:
                {
                    [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
                    //ALERTSHOW(@"你的网络异常,请检查你的网络设置");
                }
                    // 没有网络连接
                    break;
                case ReachableViaWWAN:
                    // 使用3G网络
                    [ShowMessageView showMessage:@"请求出错啦!"];
                    break;
                case ReachableViaWiFi:
                    // 使用WiFi网络
                    [ShowMessageView showMessage:@"请求出错啦!"];
                    break;
            }
            
        }];
        
    }
    else
    {
        NSString*jsonString=[dic JSONString];
        NSDictionary*request=@{@"z_data":jsonString};
        [manager POST:url parameters:request success:^(AFHTTPRequestOperation *operation, id responseObject){
            [SVProgressHUD dismiss];
            ClassData*classData=[[ClassData alloc]initWith:responseObject];
            if ([classData.number isEqualToNumber:[NSNumber numberWithInteger:2]])
            {
                ViewController*vc=[ViewController new];
                UIWindow*window=[UIApplication sharedApplication].delegate.window;
                window.rootViewController=vc;
                return ;
            }
            complete(classData);
        } failure:^(AFHTTPRequestOperation*operation, NSError *error) {
           
            [SVProgressHUD dismiss];
            Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
            switch ([reach currentReachabilityStatus]) {
                case NotReachable:
                {
                    [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
                    //ALERTSHOW(@"你的网络异常,请检查你的网络设置");
                }
                    // 没有网络连接
                    break;
                case ReachableViaWWAN:
                    // 使用3G网络
                    [ShowMessageView showMessage:@"请求出错啦!"];
                    break;
                case ReachableViaWiFi:
                    // 使用WiFi网络
                    [ShowMessageView showMessage:@"请求出错啦!"];
                    
                    break;
            }
        }];
    }
}

//创建公司上传三证
+(void)requestWithUrl:(NSString*)urlstring parameters:(NSDictionary*)dic BUSINESS:(UIImage*)img1 TAX:(UIImage*)img2 ORGANIZATION:(UIImage*)img3   finishBlock:(void(^)(ClassData*))complete
{
    [SVProgressHUD showWithStatus:@"正在拼命加载......"];
    NSString*url=[NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,urlstring];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString*jsonString=[dic JSONString];
    NSDictionary*request=@{@"z_data":jsonString};
    
    [manager POST:url parameters:request constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (img1==nil) { }
        else{
            NSData*data1=UIImageJPEGRepresentation(img1, 0.5);
            [formData appendPartWithFileData:data1 name:@"BUSINESS_LICENSE" fileName:@"img1.jpg" mimeType:@"image/jpeg"];
        }
        if (img2==nil) {}
        else{
            NSData*data2=UIImageJPEGRepresentation(img2, 0.5);
            [formData appendPartWithFileData:data2 name:@"TAX_REGISTRATION_CERTIFICATE" fileName:@"img2.jpg" mimeType:@"image/jpeg"];
        }
        if (img3==nil) {}
        else{
            NSData*data3=UIImageJPEGRepresentation(img3, 0.5);
            [formData appendPartWithFileData:data3 name:@"ORGANIZATION_CODE" fileName:@"img3.jpg" mimeType:@"image/jpeg"];
        }
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        [SVProgressHUD dismiss];
        ClassData*classData=[[ClassData alloc]initWith:responseObject];
        complete(classData);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD dismiss];
        Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
        switch ([reach currentReachabilityStatus]) {
            case NotReachable:
            {
                [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
                //ALERTSHOW(@"你的网络异常,请检查你的网络设置");
            }
                // 没有网络连接
                break;
            case ReachableViaWWAN:
                // 使用3G网络
                [ShowMessageView showMessage:@"请求出错啦!"];
                break;
            case ReachableViaWiFi:
                // 使用WiFi网络
                [ShowMessageView showMessage:@"请求出错啦!"];
                break;
        }

    }];
}
//单独拍照发布上传图片调用的方法
+(void)upImgRequestWithUrl:(NSString*)urlstring parameters:(NSDictionary*)dic image:(NSMutableArray*)image   finishBlock:(void(^)(ClassData*))complete
{
    [SVProgressHUD showWithStatus:@"正在拼命加载......"];
    NSString*url=[NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,urlstring];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString*jsonString=[dic JSONString];
    NSDictionary*request=@{@"z_data":jsonString};
    [manager POST:url parameters:request constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (image==nil) {
            
        }
        else{
            for (NSInteger i=0; i<image.count; i++) {
                NSData*data=UIImageJPEGRepresentation(image[i], 0.5);
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@%ld.jpg",str,(long)i];
                [formData appendPartWithFileData:data name:@"IMG_PATHS" fileName:fileName mimeType:@"image/jpeg"];
            }
        }
    }
    success:^(NSURLSessionDataTask *task, id responseObject) {
        ClassData*classData=[[ClassData alloc]initWith:responseObject];
        complete(classData);
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD dismiss];
        Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
        switch ([reach currentReachabilityStatus]) {
            case NotReachable:
            {
                [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
                //ALERTSHOW(@"你的网络异常,请检查你的网络设置");
            }
                // 没有网络连接
                break;
            case ReachableViaWWAN:
                // 使用3G网络
                [ShowMessageView showMessage:@"请求出错啦!"];
                break;
            case ReachableViaWiFi:
                // 使用WiFi网络
                [ShowMessageView showMessage:@"请求出错啦!"];
                break;
        }

    }];

}

// 精确 发布 发布上传图片调用的方法
+(void)upImgRequestWithUrl:(NSString*)urlstring parameters:(NSDictionary*)dic imageDataAndUrl:(NSMutableArray*)image   finishBlock:(void(^)(ClassData*))complete
{
    [SVProgressHUD showWithStatus:@"正在拼命加载......"];
    NSString*url=[NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,urlstring];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString*jsonString=[dic JSONString];
    NSDictionary*request=@{@"z_data":jsonString};
    [manager POST:url parameters:request constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (image==nil) {
            
        }
        else{
            for (NSInteger i=0; i<image.count; i++) {
                NSData*data=UIImageJPEGRepresentation(image[i], 0.5);
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@%ld.jpg",str,(long)i];
                [formData appendPartWithFileData:data name:@"TEMP_IMG_PATHS" fileName:fileName mimeType:@"image/jpeg"];
            }
        }
    }
          success:^(NSURLSessionDataTask *task, id responseObject) {
              ClassData*classData=[[ClassData alloc]initWith:responseObject];
              complete(classData);
              [SVProgressHUD dismiss];
          } failure:^(NSURLSessionDataTask *task, NSError *error) {
              [SVProgressHUD dismiss];
              Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
              switch ([reach currentReachabilityStatus]) {
                  case NotReachable:
                  {
                      [ShowMessageView showMessage:@"你的网络异常,请检查你的网络设置"];
                      //ALERTSHOW(@"你的网络异常,请检查你的网络设置");
                  }
                      // 没有网络连接
                      break;
                  case ReachableViaWWAN:
                      // 使用3G网络
                      [ShowMessageView showMessage:@"请求出错啦!"];
                      break;
                  case ReachableViaWiFi:
                      // 使用WiFi网络
                      [ShowMessageView showMessage:@"请求出错啦!"];
                      break;
              }

          }];
}


//上传崩溃日志
+(void)upIOSExceptionHandler
{
    NSString*urlString=[NSString stringWithFormat:@"%@AppUserCenter/PostSendClientLog?from=app",SERVER_ADDRESS];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSString *documents=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [documents stringByAppendingPathComponent:@"IOS_exceptionHandler.txt"];
        NSData*data=[NSData dataWithContentsOfFile:path];
        [formData appendPartWithFileData:data name:@"logFile" fileName:@"IOS_exceptionHandler.log" mimeType:@"text/*"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *documents=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [documents stringByAppendingPathComponent:@"IOS_exceptionHandler.txt"];
        NSFileManager*fileManager=[NSFileManager defaultManager];
        [fileManager removeItemAtPath:path error:nil];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
    
}

//将字符串转换为Json
+(NSDictionary*)stringToJson:(NSString*)str
{
    NSData* jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDict = [jsonData objectFromJSONData];
    NSString *jsonStr = [resultDict JSONString];
    NSDictionary*request=@{@"z_data":jsonStr};
    return request;
}


+(UIViewController *)getCurrentRootViewController {
    
    UIViewController *result;
    
    // Try to find the root view controller programmically
    
    // Find the top window (that is not an alert view or other window)
    
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    
    if (topWindow.windowLevel != UIWindowLevelNormal)
        
    {
        
        NSArray *windows = [[UIApplication sharedApplication] windows];
        
        for(topWindow in windows)
            
        {
            
            if (topWindow.windowLevel == UIWindowLevelNormal)
                
                break;
            
        }
        
    }
    
    UIView *rootView = [[topWindow subviews] objectAtIndex:0];
    
    id nextResponder = [rootView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        
        result = nextResponder;
    
    else if ([topWindow respondsToSelector:@selector(rootViewController)] && topWindow.rootViewController != nil)
        
        result = topWindow.rootViewController;
    
    else
        
        NSAssert(NO, @"ShareKit: Could not find a root view controller. You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");
    
    return result; 
    
}


@end
